use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::article_tags::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub article_id: String,
    pub tag_id: String,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Article ID must not be empty."))]
    pub article_id: String,
    #[validate(length(min = 1, message = "Tag ID must not be empty."))]
    pub tag_id: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            article_id: self.article_id.as_ref().to_owned(),
            tag_id: self.tag_id.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds an article tag by the provided id
    ///
    /// # Errors
    ///
    /// When could not find article tag or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let article_tag = article_tags::Entity::find()
            .filter(
                model::query::condition()
                    .eq(article_tags::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        article_tag.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds article tags by the provided article_id
    ///
    /// # Errors
    ///
    /// When could not find article tags or DB query error
    pub async fn find_by_article_id(
        db: &DatabaseConnection,
        article_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let article_tags = article_tags::Entity::find()
            .filter(
                model::query::condition()
                    .eq(article_tags::Column::ArticleId, article_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(article_tags)
    }

    /// finds article tags by the provided tag_id
    ///
    /// # Errors
    ///
    /// When could not find article tags or DB query error
    pub async fn find_by_tag_id(db: &DatabaseConnection, tag_id: &str) -> ModelResult<Vec<Self>> {
        let article_tags = article_tags::Entity::find()
            .filter(
                model::query::condition()
                    .eq(article_tags::Column::TagId, tag_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(article_tags)
    }

    /// Asynchronously creates an article tag and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the article tag into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let txn = db.begin().await?;

        let article_tag = article_tags::ActiveModel {
            article_id: ActiveValue::set(params.article_id.to_string()),
            tag_id: ActiveValue::set(params.tag_id.to_string()),
            ..Default::default()
        }
        .insert(&txn)
        .await?;

        txn.commit().await?;

        Ok(article_tag)
    }
}
